$(document).ready(function () {
    hidePageTitlePageDefault();
    jQuery(window).scroll(function () {
        if (jQuery(this).scrollTop() > 200) {
            jQuery('#footerContent .backtotop').fadeIn(500);
        } else {
            jQuery('#footerContent .backtotop').fadeOut(500);
        }
    });

    jQuery('#footerContent .backtotop').click(function (event) {
        event.preventDefault();
        jQuery('html, body').animate({ scrollTop: 0 }, 500);
        return false;
    });
});

function hidePageTitlePageDefault() {
    var currurl = window.location.pathname;
    var index = currurl.lastIndexOf("/") + 1;
    var filename = currurl.substr(index);

    if (filename !== null) {
        var pageName = filename.replace('.aspx', '');
        if (pageName === 'default') {
            if ($(".titlePage") !== null) {
                $(".titlePage").hide();
            }
            if ($("#contentRow") !== null) {
                $("#contentRow").attr("style", "margin-top:40px");
            }
        }
    }
}

function getRowLimitFromContentEditorWP(currentId) {
    var closestParent = $('#' + currentId).closest("div.ms-WPBody.ms-wpContentDivSpace[allowdelete='false']").first();
    if (closestParent !== null && closestParent.length > 0) {
        var contentEditorId = closestParent.parents("div.ms-webpart-chrome.ms-webpart-chrome-vertical.ms-webpart-chrome-fullWidth").first();
        if (contentEditorId !== null && contentEditorId.length > 0) {
            var chromeType = contentEditorId.find("div.ms-webpart-chrome-title:first-child");
            if (chromeType !== null && chromeType.length > 0) {
                var webpartFullTitle = contentEditorId.find("div.ms-webpart-chrome-title:first-child > span:first-child").attr("title");
                if (webpartFullTitle !== null && webpartFullTitle.length > 0) {
                    var titleValue = webpartFullTitle.replace(" - Allows authors to enter rich text content.", "");
                    if ($.trim(titleValue) !== '' && titleValue.indexOf('[') > 0) {
                        titleValue = titleValue.substring(0, titleValue.indexOf('['));
                    }
                    //hide webpart title
                    chromeType.hide();
                    return parseInt($.trim(titleValue)) || 5;
                }
            }



        }
    }
    return 5;
}

String.prototype.toNumber = function () {
    return parseInt(this, 10);
};

//Get query string
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
};

function hideLeftMenuOnRootSite() {
    var siteUrl = _spPageContextInfo.siteServerRelativeUrl;
    var webUrl = _spPageContextInfo.webServerRelativeUrl;
    if (siteUrl === webUrl) $('#sideNavBox').hide();
};
// Function to retrieve a query string value.
// For production purposes you may want to use
// a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
};

//Replace Nguyen Thi Thanh Hien Nguyen Thi (ManPower)
function replaceUserNameNguyenThiThanhHien(userName) {
    var hienName = 'Nguyen Thi Thanh Hien Nguyen Thi (ManPower)';
    if ($.trim(userName.toUpperCase()) === hienName.toUpperCase()) {
        return 'Hien Nguyen';
    }
    return userName;
}
//Update URl parameter
function updateURLParameter(url, param, paramVal) {
    var theAnchor;
    var newAdditionalUrl = "";
    var tempArray = url.split("?");
    var baseUrl = tempArray[0];
    var additionalUrl = tempArray[1];
    var temp = "";
    var tmpAnchor;
    var theParams;
    if (additionalUrl) {
        tmpAnchor = additionalUrl.split("#");
        theParams = tmpAnchor[0];
        theAnchor = tmpAnchor[1];
        if (theAnchor)
            additionalUrl = theParams;

        tempArray = additionalUrl.split("&");

        for (var i = 0; i < tempArray.length; i++) {
            if (tempArray[i].split('=')[0] != param) {
                newAdditionalUrl += temp + tempArray[i];
                temp = "&";
            }
        }
    }
    else {
        tmpAnchor = baseUrl.split("#");
        theParams = tmpAnchor[0];
        theAnchor = tmpAnchor[1];

        if (theParams)
            baseUrl = theParams;
    }

    if (theAnchor)
        paramVal += "#" + theAnchor;

    var rowsTxt = temp + "" + param + "=" + paramVal;
    return baseUrl + "?" + newAdditionalUrl + rowsTxt;
}

function redirectToSkillPage() {
    var personalSkillsId = $('#ID_PersonalSkills');
    if (personalSkillsId !== null) {
        window.location.href = '/sites/PMO/Pages/personalskills.aspx';
    }
}

function onHoverlistviewtable() {
    var listviewtableBody = $('.ms-listviewtable tbody tr');
    if (listviewtableBody != null) {
        $('.ms-listviewtable tbody tr').hover(
       function () {
           var _this = $(this);
           _this.prev().find('td:first-child').css({ "border-bottom": "1px solid #e9e9e9" });
           _this.prev().find('td:last-child').css({ "border-bottom": "1px solid #e9e9e9" });
       },
       function () {
           var _this = $(this);
           if (!_this.is(':first-child')) {
               _this.prev().find('td:first-child').css({ "border-bottom": "1px solid transparent" });
               _this.prev().find('td:last-child').css({ "border-bottom": "1px solid transparent" });
           }
       }
   );
    }
}

function onAddNewColumnAtTheEndofListviewtable() {

    //Not apply for ms-listviewgrid table
    var listviewTable = $('table.ms-listviewtable');
    if (listviewTable.length > 0) {
        listviewTable.each(function () {
            if ($(this).attr('class').indexOf('ms-listviewgrid') > -1)
                return true;

            if ($(this).find('table.ms-listviewtable.ms-listviewgrid').length > 0)
                return true;

            //only apply for list view table
            var listViewHasGroup = $(this).find('tbody[isloaded="true"]');

            if (listViewHasGroup.length > 0) {//has group
                listViewHasGroup.each(function () {
                    var row = $(this).find('tr');
                    row.each(function () {
                        var lastcolumn = $(this).find('td:last-child');
                        if (lastcolumn.length > 0 && lastcolumn.hasClass('ms-tdLast') === false) {
                            $(this).append('<td class="ms-tdLast"></td>');
                        }
                    });
                });
            } else {    //No group
                var tbodyNoGroup = $(this).find('tbody');
                tbodyNoGroup.each(function () {
                    var rowNoGroup = $(this).find('tr');
                    rowNoGroup.each(function () {
                        var lastcolumnNoGroup = $(this).find('td:last-child');
                        if (lastcolumnNoGroup.length > 0 && lastcolumnNoGroup.hasClass('ms-tdLast') === false) {
                            $(this).append('<td class="ms-tdLast"></td>');
                        }
                    });
                });
            }

            //Add th with normal user
            var thLastChild = $(this).find('thead tr.ms-viewheadertr th:last-child');
            if (thLastChild !== null && thLastChild.length > 0) {
                var thMsvh2 = thLastChild.hasClass("ms-vh2");
                var thMsvh = thLastChild.hasClass("ms-vh");
                var thMsvh2Nofilter = thLastChild.hasClass("ms-vh2-nofilter");
                if (thMsvh2 === true || thMsvh === true || thMsvh2Nofilter === true) {
                    var rowcol = $(this).find('thead tr.ms-viewheadertr');
                    if (rowcol.length > 0) rowcol.append('<th></th>');
                }
            }
            return false;
        });
    }
}

function onEnablePictureLibrarySlideShow() {
    var fullUrl = window.location.href;
    //Picture library
    if (fullUrl.lastIndexOf("/Gallery/Forms/Thumbnails.aspx?RootFolder=") >= 0) {
        //bind data-lightbox into a tag
        var mstileviewtilecontent = $("div .ms-tileview-tile-content a");
        if (mstileviewtilecontent !== null && mstileviewtilecontent !== 'undefined') {
            mstileviewtilecontent.each(function () {
                var idList = '#' + $(this).attr('id');

                //Get Big Picture
                var imgsrc = $(idList).parent().find('img:first-child').attr('src');
                if (imgsrc === '/_layouts/15/images/256_folder.png') return true;
                var orerrorString = $(idList).parent().find('img:first-child').attr('onerror');
                if (orerrorString === "displayGenericDocumentIcon(event.srcElement ? event.srcElement : event.target, 1); return false;") return true;

                if (imgsrc === '/Style%20Library/Media%20Player/VideoPreview.png') return true;
                //Video
                var valueVideo = "/Preview%20Images";
                if (imgsrc.indexOf(valueVideo) != -1) return true;
                var removeTail = imgsrc.substring(0, imgsrc.lastIndexOf('.'));
                var getTail = removeTail.substring(imgsrc.lastIndexOf('_'));
                getTail = getTail.replace("_", "");
                var valuePicture = imgsrc.substring(imgsrc.lastIndexOf('_'));
                var imgsrcNew = imgsrc.replace(valuePicture, "." + getTail);
                imgsrcNew = imgsrcNew.replace("/_w/", "/");

                $(idList).attr("href", imgsrcNew);
                $(idList).attr("hrefaction", imgsrcNew);
                $(idList).attr("data-lightbox", "companyPictureLibrary");
                $(idList).attr('onclick', null);
                $(idList).attr('clickaction', null);
                return true;
            });
        }
    }
}